/** 内部配置（只读） */
import type { UnConfig, UnResponse } from '@uni-helper/uni-network'
import { isMatch } from '@/utils/is'
import { joinUrls } from '@/utils/truncate'

export interface Response {
  message: string
  data?: any
}

const config: {
  /** 环境配置 */
  readonly env: {
    /** API服务器地址 */
    readonly viteBaseApi: string
    /** 是否启动本地mock */
    readonly viteUseMock: boolean
  }
  /** 服务端配置 */
  readonly service: {
    /** 服务端白名单，放置一些不需要`token`的接口（支持正则） */
    readonly whiteList: string[]
    /** API相关配置 */
    readonly api: {
      /** 请求地址处理 */
      readonly url: (reqConfig: UnConfig) => string
      /** 响应请求处理 */
      readonly response: (res: UnResponse<any, any>) => Response
    }
  }
  /**
   * z-pagin配置
   * https://z-paging.zxlee.cn/api/props/global-config.html
   */
  readonly zPaging: Recordable
} = {
  env: {
    viteBaseApi: import.meta.env.VITE_BASE_API ?? '',
    viteUseMock: !!import.meta.env.VITE_USE_MOCK,
  },
  service: {
    whiteList: [
      '/access/refresh-token',
      '/access/login/phone',
      '/access/login/account',
      '/access/login/send-sms',
    ],
    api: {
      url: (reqConfig) => {
        // mock忽略列表，开启的时候生效。支持正则表达式
        const ignores: string[] = []

        reqConfig.url = reqConfig.url || ''
        if (config.env.viteUseMock && !isMatch(ignores, reqConfig.url)) {
          return reqConfig.url
        }
        else {
          return joinUrls(
            config.env.viteBaseApi,
            'api/app',
            reqConfig.url || '',
          )
        }
      },
      response: (res) => {
        if (res) {
          if (!res.data?.success) {
            throw new Error(res.data?.message || '请求未响应，请稍候重试')
          }
          else {
            return { message: res.data?.message, data: res.data?.data }
          }
        }
        else {
          return { message: '请求异常，请稍候重试', data: null }
        }
      },
    },
  },
  zPaging: {
    config: {
      'default-page-size': 10,
      'empty-view-text': '资料暂无',
      'hide-no-more-by-limit': 10,
    },
  },
}

export default config
